//
//  AnswerViewController.m
//  DriveStudy
//
//  Created by chen on 2017/4/14.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "AnswerViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface AnswerViewController ()<SheetViewDelegate>{
    AnswerScrollView *scrollerView;
    SelectModelView *selectModelView;
    SheetView *sheetView;
    int _currentPage;
    NSTimer *_timer;
    UILabel *_timerLabel;
}

@end

@implementation AnswerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    //右边导航栏创建
    [self createModelView];
   
    [self createData];
    
    [self.view addSubview:scrollerView];
    
    
    //创建抽屉视图
    [self createSheetView];
    //代理服务
    sheetView.delegate = self;
}
-(void)createData{
    //加载数据源
    FirstLevelBL *bl = [FirstLevelBL new];
    NSArray *array = [bl findAll:answer];
    if (_type == 1) {
        
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        for (int i= 0 ; i<array.count-1; i++) {
            AnswerModel *model = array[i];
            if ([model.pid isEqualToString: _number]) {
                [arr addObject:model];
            }
        }
        scrollerView = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 60) withDataArray:arr andCurrentPage:_currentPage];
    }else if (_type == 2){
        NSArray *array = [bl findAll:answer];
        scrollerView = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 60) withDataArray:array andCurrentPage:_currentPage];
    }else if (_type == 3){
        //随机联系的思路就是在设计一个临时数组，然后通过随机函数将取出的数值放在一个新的数组中。
        NSMutableArray *tempArr = [[NSMutableArray alloc]init];
        [tempArr addObjectsFromArray:array];
        NSMutableArray *dataArr = [[NSMutableArray alloc]init];
        for (int i= 0 ; i<tempArr.count;) {
            int index = arc4random()%(tempArr.count);
            [dataArr addObject:tempArr[index]];
            [tempArr removeObjectAtIndex:index];
        }
        scrollerView = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 60) withDataArray:dataArr andCurrentPage:_currentPage];
    }else if(_type == 4){
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        for (int i= 0 ; i<array.count-1; i++) {
            AnswerModel *model = array[i];
            if ([model.sid isEqualToString:_number]) {
                [arr addObject:model];
            }
        }
        scrollerView = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 60) withDataArray:arr andCurrentPage:_currentPage];
    }else if (_type == 5){
        //随机联系的思路就是在设计一个临时数组，然后通过随机函数将取出的数值放在一个新的数组中。
        NSMutableArray *tempArr = [[NSMutableArray alloc]init];
        [tempArr addObjectsFromArray:array];
        NSMutableArray *dataArr = [[NSMutableArray alloc]init];
        for (int i= 0 ; i<100;i++) {
            int index = arc4random()%(tempArr.count);
            [dataArr addObject:tempArr[index]];
            [tempArr removeObjectAtIndex:index];
        }
        scrollerView = [[AnswerScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 60) withDataArray:dataArr andCurrentPage:_currentPage];
        [self createNavBar];
    }
    if (_type == 5) {
        [self createTestToolBar];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runTimer) userInfo:nil repeats:YES];
        _timerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
        _timerLabel.text = @"60:00";
        _timerLabel.textAlignment = NSTextAlignmentCenter;
        self.navigationItem.titleView = _timerLabel;
        
    }else{
        [self createToolBar];
    }
}
-(void)runTimer{
    static int Time = 3600;
    Time --;
    _timerLabel.text = [NSString stringWithFormat:@"%d:%d",Time/60,Time%60];
}
-(void)createNavBar{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]init];
    leftItem.title = @"返回";
    [leftItem setTarget:self];
    [leftItem setAction:@selector(clickNavBarButton:)];
    leftItem.tag = 0;
    self.navigationItem.leftBarButtonItem = leftItem;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]init];
    rightItem.title = @"交卷";
    [rightItem setTarget:self];
    rightItem.tag = 1;
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem setAction:@selector(clickNavBarButton:)];
}
-(void)clickNavBarButton:(UIBarButtonItem *)btn{
    switch (btn.tag) {
        case 0:
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"时间还有很多，您确认要提交吗?" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"交卷离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"交卷离开");
                [self.navigationController popViewControllerAnimated:YES];
            }];
            UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"再看看" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"再看看");
            }];
            [alert addAction:yesAction];
            [alert addAction:noAction];
            [self presentViewController:alert animated:true completion:nil];
        }
            break;
        case 1:
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"时间还有很多，您确认要提交吗?" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"交卷离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"交卷离开");
                [self.navigationController popViewControllerAnimated:YES];
            }];
            UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"再看看" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"再看看");
            }];
            [alert addAction:yesAction];
            [alert addAction:noAction];
            [self presentViewController:alert animated:true completion:nil];
        }
            break;
        default:
            break;
    }
}
-(void)createSheetView{
    sheetView = [[SheetView alloc]initWithFrame:CGRectMake(0, HEIGHT, WIDTH, HEIGHT - 80) withSuperView:self.view andQuestion:100];
    [self.view addSubview:sheetView];
}
-(void)createToolBar{
    NSArray *arr_label = @[[NSString stringWithFormat:@"%lu",(unsigned long)scrollerView.dataArray.count],@"查看答案",@"收藏本题"];
    UIView *barView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 64 - 60, self.view.frame.size.width, 60)];
    barView.backgroundColor = [UIColor whiteColor];
    for (int i= 0; i< 3 ; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(self.view.frame.size.width/3*i + self.view.frame.size.width/3/2 - 20, 0, 40, 40);
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i+16]] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d-2.png",i+16]] forState:UIControlStateHighlighted];
        btn.tag = i;
        [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [barView addSubview:btn];
        //添加下面的文字
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(btn.center.x - 25, 40, 50, 18)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.text = arr_label[i];
        [barView addSubview:label];
    }
    [self.view addSubview:barView];
}
-(void)createTestToolBar{
    NSArray *arr_label = @[[NSString stringWithFormat:@"%lu",(unsigned long)scrollerView.dataArray.count],@"收藏本题"];
    UIView *barView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 64 - 60, self.view.frame.size.width, 60)];
    barView.backgroundColor = [UIColor whiteColor];
    for (int i= 0; i< 2 ; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(self.view.frame.size.width/2*i + self.view.frame.size.width/2/2 - 20, 0, 40, 40);
        if (i==0) {
            [btn setBackgroundImage:[UIImage imageNamed:@"16.png"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"16-2.png"] forState:UIControlStateHighlighted];
            btn.tag = 0;
        }else{
            [btn setBackgroundImage:[UIImage imageNamed:@"18.png"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"18-2.png"] forState:UIControlStateHighlighted];
            btn.tag = 2;
        }
        [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [barView addSubview:btn];
        //添加下面的文字
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(btn.center.x - 25, 40, 50, 18)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.text = arr_label[i];
        [barView addSubview:label];
    }
    [self.view addSubview:barView];
}
-(void)click:(UIButton *)button{
    switch (button.tag) {
        case 0:
        {
            [UIView animateWithDuration:0.3 animations:^{
                sheetView.frame = CGRectMake(0, 80, WIDTH, HEIGHT - 80);
                sheetView.backView.alpha = 0.8;
            }];
        }
            break;
        case 1:
        {
            //先看当前这道题是不是答过了，如果打过了就不显示
            if ([scrollerView.hasAnswerArray[scrollerView.currentPage] intValue]!=0) {
                return;
            }else{
                AnswerModel *model = scrollerView.dataArray[scrollerView.currentPage];
                NSString *num = model.manswer;
                char an_char = [num characterAtIndex:0];
                if ([model.mtype intValue] == 1) {
                    [scrollerView.hasAnswerArray replaceObjectAtIndex:scrollerView.currentPage withObject:[NSString stringWithFormat:@"%d",an_char - 'A' +1]];
                }else{
                    [scrollerView.hasAnswerArray replaceObjectAtIndex:scrollerView.currentPage withObject:[NSString stringWithFormat:@"%d",[num isEqual:@"对"]?0:1]];
                }
                
            }
            [scrollerView reloadData];
        }
            break;
        case 2:
        {
            NSArray *arr = [UserDefaultManager getCollectQuestion];
            if ([arr containsObject:[NSString stringWithFormat:@"%d",scrollerView.currentPage +1]]) {
                [self showMessage:@"已收藏,请勿重复收藏！"];
            }else{
                [UserDefaultManager addWrongQuestion:[NSString stringWithFormat:@"%d",scrollerView.currentPage +1]];
                [self showMessage:@"收藏成功！"];
            }
        }
            break;
        default:
            break;
    }
    
}
-(void)showMessage:(NSString *)message{
    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 225, 120, 30)];
    // 设置提示内容
    [tipLabel setText:message];
    tipLabel.backgroundColor = [UIColor blackColor];
    tipLabel.layer.cornerRadius = 5;
    tipLabel.layer.masksToBounds = YES;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:tipLabel];
    // 设置时间和动画效果
    [UIView animateWithDuration:2.0 animations:^{
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        // 动画完毕从父视图移除
        [tipLabel removeFromSuperview];
    }];
}
-(void)createModelView{
    NSArray *itemArray = @[@"答题模式",@"背题模式"];
    selectModelView = [[SelectModelView alloc]initWithFrame:self.view.frame andTouch:^(SelectModel model){
        NSLog(@"%u",model);
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:itemArray[model] style:UIBarButtonItemStylePlain target:self action:@selector(modelChange:)];
        self.navigationItem.rightBarButtonItem = item;
        selectModelView.alpha = 0.0;
    }];
    selectModelView.alpha = 0.0;
    [self.view addSubview:selectModelView];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:itemArray[0] style:UIBarButtonItemStylePlain target:self action:@selector(modelChange:)];
    self.navigationItem.rightBarButtonItem = item;
}
-(void)modelChange:(UIBarButtonItem *)item{
    [UIView animateWithDuration:0.5 animations:^{
        selectModelView.alpha = 1;
    }];
}
#pragma mark - SheetViewDelegate协议方法
-(void)SheetViewClick:(int)index{
    NSLog(@"选择的index选项：%d",index);
    _currentPage = index;
    //通过改变scrollview的位移量来控制scrollerView中的滑动方法。
    UIScrollView *scroll = scrollerView.scrollview;
    scroll.contentOffset = CGPointMake(index * scroll.frame.size.width, 0);
    [scroll.delegate scrollViewDidEndDecelerating:scroll];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
